package com.systop.front.message.controller;


import com.aliyuncs.utils.StringUtils;
import com.systop.commer.ResponseResult;
import com.systop.front.message.service.Smsservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域
public class SmsController {
    @Autowired
    private Smsservice smsservice;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send")
    public String code(@RequestParam(value = "phone") String phone) {
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return phone + ":" + code + "已存在，还没有过期";

        }
        //生成验证码
        code = UUID.randomUUID().toString().substring(0, 6);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = smsservice.send(phone, "SMS_199195187", param);
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 180, TimeUnit.SECONDS);
            return phone + ":" + code + "发送成功";
        } else {
            return "发送失败!";
        }
    }


    @GetMapping("/sendcode")
    public @ResponseBody ResponseResult codesend(@RequestParam(value = "phone") String phone, @RequestParam(value = "codes") String codes) {
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println(phone);
        System.out.println(code);
        System.out.println(codes);
            if(codes.equals(code)){
                return ResponseResult.build(200, "成功");
        }else{
                return ResponseResult.build(500, "失败");
            }

     }


}